import { createApp, h, render } from 'vue';
import RechargeDialog from '@/components/RechargeDialog.vue';

interface RechargeDialogOptions {
  title?: string;
  message?: string;
  cancelText?: string;
  confirmText?: string;
  closeOnMaskClick?: boolean;
  onConfirm?: () => void;
  onCancel?: () => void;
  onClose?: () => void;
}

// 创建一个弹窗实例
const createRechargeDialog = (options: RechargeDialogOptions = {}) => {
  // 创建一个容器元素
  const container = document.createElement('div');
  document.body.appendChild(container);

  // 默认配置
  const defaultOptions = {
    title: '算力充值',
    message: '你的算力余额为0，请尽快联系客服进行充值',
    cancelText: '知道了',
    confirmText: '去充值',
    closeOnMaskClick: true,
    onConfirm: () => {},
    onCancel: () => {},
    onClose: () => {}
  };

  // 合并配置
  const mergedOptions = { ...defaultOptions, ...options };

  // 创建弹窗实例
  const dialogApp = createApp({
    render() {
      return h(RechargeDialog, {
        visible: true,
        title: mergedOptions.title,
        message: mergedOptions.message,
        cancelText: mergedOptions.cancelText,
        confirmText: mergedOptions.confirmText,
        closeOnMaskClick: mergedOptions.closeOnMaskClick,
        onConfirm: () => {
          mergedOptions.onConfirm?.();
          destroyDialog();
        },
        onCancel: () => {
          mergedOptions.onCancel?.();
          destroyDialog();
        },
        onClose: () => {
          mergedOptions.onClose?.();
          destroyDialog();
        }
      });
    }
  });

  // 销毁弹窗的方法
  const destroyDialog = () => {
    dialogApp.unmount();
    if (container.parentNode) {
      container.parentNode.removeChild(container);
    }
  };

  // 挂载弹窗
  dialogApp.mount(container);

  // 返回销毁方法，以便外部可以手动关闭弹窗
  return {
    close: destroyDialog
  };
};

// 导出弹窗服务
export const rechargeDialog = {
  show: createRechargeDialog,
  
  // 快捷方法：显示算力不足提示
  showLowBalance(options: RechargeDialogOptions = {}) {
    return createRechargeDialog({
      title: '算力充值',
      message: '你的算力余额为0，请尽快联系客服进行充值',
      ...options
    });
  }
};

export default rechargeDialog;